<template>
  <el-button class="reportButton" type="primary" @click="report()">
    <div class="btnContent">
      <img class="updown" src="@/assets/icon/updown.png" alt="">
      导出
    </div>
  </el-button>
</template>

<script>
export default {
  name: 'ReportButton',
  props: {
    reportData: {
      type: Object,
      default: {}
    },
    filename: {
      type: String,
      default: ''
    },
    apiAddress: {
      type: Function,
      default: null
    },
  },
  methods: {
    report() {
      if (this.apiAddress) {
        this.apiAddress(this.reportData).then(response => {
          let blob = response.data;
          let filename = '';
          if (this.filename) {
            // 默认值，以防头部没有文件名
            filename = this.filename;
          } else {
            //从 Content-Disposition 头部获取文件名
            if (response.headers['content-disposition']) {
              const disposition = response.headers['content-disposition'];
              const filenameMatch = disposition.match(/filename="?([^"]+)"?/);
              if (filenameMatch && filenameMatch[1]) {
                filename = filenameMatch[1];
              }
            }
          }
          filename = filename ? filename : '文件'
          // 创建一个链接并下载文件
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          // 使用从头部获取的文件名或者props传入的
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放 URL 对象
          URL.revokeObjectURL(link.href);
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.reportButton {
  width: 79px;
  height: 32px;
  background: #6176D0;
  border-radius: 5px;
  padding: 0;
  margin: 0 10px;
  display: flex;
  justify-content: center;
  align-items: center;

  .btnContent {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .updown {
    width: 16px;
    height: 16px;
    margin-right: 5px;
  }
}
</style>